package metagen;

import java.util.List;
import java.util.Random;

import main.MetaGen;


/**
 */
public class Union implements MetaGen {
    private MetaGen[] metas;
    private Random rand;

    public Union(List<MetaGen> metas) {
        if (metas.size() < 2) {
            throw new RuntimeException("Union must have at least 2 regexps as arguments!");
        }
        for (MetaGen meta : metas) {
            if (meta == null) {
                throw new RuntimeException("Every alternation in union must be non-null!");
            }
        }
        this.metas = new MetaGen[metas.size()];
        metas.toArray(this.metas);
        this.rand = new Random();
    }

    public Union(MetaGen... metas) {
        if (metas.length < 2) {
            throw new RuntimeException("Union must have at least 2 regexps as arguments!");
        }
        for (MetaGen meta : metas) {
            if (meta == null) {
                throw new RuntimeException("Every alternation in union must be non-null!");
            }
        }
        this.metas = metas;
        this.rand = new Random();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("(?:");
        boolean first = true;
        for (MetaGen meta : metas) {
            if (first) {
                first = false;
            } else {
                sb.append("|");
            }
            sb.append(meta.toString());
        }
        sb.append(")");
        return sb.toString();
    }

    public String randGen() {
        // �����ѡ��� regexp ֮һ����ƥ���ַ�
        int idx = rand.nextInt(metas.length);
        return metas[idx].randGen();
    }

    public void setMetas(MetaGen[] metas) {
        this.metas = metas;
    }

    public void setRand(Random rand) {
        this.rand = rand;
    }
}
